package org.feng.navigation.generator.util;

import org.springframework.util.ResourceUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;

/**
 * 文件操作工具类
 *
 * @version V1.0
 * @author: junzi
 * @date: 2023年02月07日 15时14分
 */
public class FileUtil {

    /**
     * 类路径下的资源文件夹中的文件完整URL
     *
     * @param url 比如 resources 中有文件 templates/GeneratorEnum.java.ftl
     * @return 指定url的文件
     */
    public static File getFileByResourceUrl(String url) {
        try {
            return ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX.concat(url));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public static void writeFileToDisk(String resultStr, String dir, String fileName) {
        // 获取目标文件夹
        File dirFile = getFileByResourceUrl(dir);
        System.out.println(dirFile.getName());
        String absolutePath = dirFile.getAbsolutePath();
        try (BufferedWriter writer = Files.newBufferedWriter(Path.of(absolutePath , fileName), StandardCharsets.UTF_8)) {
            writer.write(resultStr);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
